package com.packet.cheng;
/**
 @author zaicheng
 @version 1.0
 @date 2022-04-19
 @email zzc15847256473@163.com
 */

import com.packet.cheng.entity.User;

import java.util.ArrayList;
import java.util.List;

public class TestCreateObject {

    public static void main(String[] args) throws Exception {

        // AService存储一批数据
        List<Integer> data = new ArrayList<>();
        for (int i = 1; i <= 100; i++){
            data.add(i);
        }
        AService aService = new AService();
        // a中存储的数据
        List<Integer> aData = aService.get(data);

        BService bService = new BService(aService);
        // B函数的入参数据
        List<Integer> param = new ArrayList<>();
        // 这里为入参150时，就会为错
        for (int i = 1; i <= 100; i++){
            param.add(i);
        }
        List<Integer> result = bService.get(param);
        for (Integer i : result){
            System.out.print(i+"\t");
        }
    }

    // 反射创建对象
    public  static void  reflectObject(){

        long start = System.currentTimeMillis();
        int i;
        for (i=0;i<100000000;i++){
            User user = new User();
        }
        if (i == 100000000){
            long end = System.currentTimeMillis();
            System.out.println("new对象耗时为："+(end-start)+"ms");
        }


    }

    // new创建对象
    public static void  commonObject() throws IllegalAccessException, InstantiationException {

        long start = System.currentTimeMillis();
        int i;
        Class<User> userClass = User.class;
        for (i = 0; i < 100000000;i++){
            User user = userClass.newInstance();
        }
        if (i == 100000000){
            long end = System.currentTimeMillis();
            System.out.println("反射创建对象耗时为："+(end-start)+"ms");
        }
    }


    static  class  AService{
        public  List<Integer>  get(List<Integer> ids){
            return ids;
        }
    }


    static  class  BService{
        private  AService aService;
        public BService(AService aService) {
            this.aService = aService;
        }
        public List<Integer> get(List<Integer> ids) throws Exception {
            if (ids.size() > 100){
                throw new Exception("最多支持100个id的查询");
            }
            List<Integer> result = new ArrayList<>();
            // 每批处理的数据量
            int perBatchSize = 10;
            // 计算需要分多少批
            // int  batchSize =  ids.size() /  perBatchSize;
            // 遍历每一批
            for (int i = 0; i < ids.size(); i+=perBatchSize) {
                // 这一批结束的索引，如果最后一批不足10个，使用总数量作为结束索引
                int endIndex = Math.min(i + perBatchSize, ids.size());
                // 从AService获取这一批的数据
                List<Integer> batchResult = aService.get(ids.subList(i, endIndex));
                // 将这一批的数据添加到结果中
                result.addAll(batchResult);
            }
            return  result;
        }
    }
}
